/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */
package com.fuyao.cloud.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.admin.api.dto.UserInfoParamsDTO;
import com.fuyao.cloud.admin.api.entity.SysUser;
import com.fuyao.cloud.admin.api.entity.SysUserinfo;
import com.fuyao.cloud.admin.api.vo.UserInfoDeptVO;
import com.fuyao.cloud.admin.api.vo.UserinfoExportVO;
import com.fuyao.cloud.admin.constant.UserConstants;
import com.fuyao.cloud.admin.service.SysUserService;
import com.fuyao.cloud.common.core.util.DictItemOption;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.resolver.DictItemResolver;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.admin.service.SysUserinfoService;
import com.fuyao.cloud.common.security.annotation.Inner;
import com.fuyao.cloud.common.security.service.CloudUser;
import com.fuyao.cloud.common.security.util.SecurityUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 人员信息
 *
 * @author 碎月
 * @date 2021-12-16 10:32:13
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/sysuserinfo" )
@Api(value = "sysuserinfo", tags = "人员信息管理")
public class SysUserinfoController {

    private final SysUserinfoService sysUserinfoService;

    private final SysUserService userService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param userinfo 人员信息
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('admin_sysuserinfo_view')" )
    public R getSysUserinfoPage(Page page, SysUserinfo userinfo) {
        QueryWrapper wrapper =new QueryWrapper();
        if (userinfo.getMobile()!=null){
            wrapper.eq("MOBILE",userinfo.getMobile());
        }
        if (userinfo.getPersonNumber()!=null){
            wrapper.eq("PERSON_NUMBER",userinfo.getPersonNumber());
        }
        if (userinfo.getName()!=null){
            wrapper.like("NAME",userinfo.getName());
        }
        if (userinfo.getType()!=null){
            wrapper.like("TYPE",userinfo.getType());
        }
        wrapper.orderByDesc("create_time","update_time");
        return R.ok(sysUserinfoService.page(page, wrapper));
    }


    /**
     * 通过id查询人员信息
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('admin_sysuserinfo_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(sysUserinfoService.getById(id));
    }

    @ApiOperation(value = "通过userid查询", notes = "通过userid查询")
    @GetMapping("/getByUserId/{userId}")
    public R getByUserId(@PathVariable("userId" ) Long userId) {
        LambdaQueryWrapper<SysUserinfo> eqQueryWrapper = Wrappers.<SysUserinfo>query().lambda().eq(SysUserinfo::getUserId, userId);
        SysUserinfo userInfo = this.sysUserinfoService.getOne(eqQueryWrapper, false);
        return R.ok(userInfo);
    }

    @Inner
    @ApiOperation(value = "通过 userName 查询", notes = "通过 userName 查询")
    @GetMapping("/getUserInfoByUserName/{userName}")
    public R getUserInfoByUserName(@PathVariable("userName") String userName) {
        SysUserinfo userInfo = this.sysUserinfoService.getUserInfoByUserName(userName);
        return R.ok(userInfo);
    }

    /**
     * 新增人员信息
     * @param sysUserinfo 人员信息
     * @return R
     */
    @ApiOperation(value = "新增人员信息", notes = "新增人员信息")
    @SysLog("新增人员信息" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin_sysuserinfo_add')" )
    public R save(@RequestBody SysUserinfo sysUserinfo) {
        if (sysUserinfoService.save(sysUserinfo)){
            return R.ok(sysUserinfo.getId());
        }
        return R.ok(0);
    }

    /**
     * 修改人员信息
     * @param sysUserinfo 人员信息
     * @return R
     */
    @ApiOperation(value = "修改人员信息", notes = "修改人员信息")
    @SysLog("修改人员信息")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin_sysuserinfo_edit')")
    public R updateById(@RequestBody SysUserinfo sysUserinfo) {
        return R.ok(sysUserinfoService.updateById(sysUserinfo));
    }

    /**
     * 通过id删除人员信息
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除人员信息", notes = "通过id删除人员信息")
    @SysLog("通过id删除人员信息" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('admin_sysuserinfo_del')")
    public R removeById(@PathVariable Long id) {
        return R.ok(sysUserinfoService.removeById(id));
    }


    /**
     * 导出excel 表格
     * @param sysUserinfo 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @PostMapping("/export")
    @PreAuthorize("@pms.hasPermission('admin_sysuserinfo_export')" )
    public List<UserinfoExportVO> export(SysUserinfo sysUserinfo) {
        List<SysUserinfo> userinfoList = sysUserinfoService.list(Wrappers.query(sysUserinfo));
        Map<String, List<DictItemOption>> resultMap = DictItemResolver.getDictOptionResultMap("gender");
        if(CollUtil.isNotEmpty(userinfoList)){
            return userinfoList.stream().map(userinfo -> {
                UserinfoExportVO exportVO = new UserinfoExportVO();
                BeanUtil.copyProperties(userinfo,exportVO);
                exportVO.setGender( DictItemResolver.getDictOptionLabel(resultMap.get("gender"),exportVO.getGender()));
                return exportVO;
            }).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    /**
     * 修改为退休人员
     * @param id
     * @return
     */
    @GetMapping("/retireUser/{id}")
    public R retireUser(@PathVariable("id") Long id){
        SysUserinfo condition = this.sysUserinfoService.getById(id);
        SysUser user =new SysUser();
        user.setUserId(condition.getUserId());
        user.setLockFlag(UserConstants.USER_LOCKED);
        this.userService.updateById(user);
        condition.setId(id);
        condition.setRetireDate(LocalDate.now());
        condition.setType(UserConstants.USER_RETIRE);
        return R.ok(sysUserinfoService.updateById(condition));
    }

    /**
     * 根据用户编码查询用户信息
     * @param number 用户编码
     * @return
     */
    @GetMapping("/details/number/{number}")
    public R getByPersonnelNum(@PathVariable String number) {
        SysUserinfo condition = new SysUserinfo();
        condition.setPersonNumber(number);
        return R.ok(sysUserinfoService.getOne(new QueryWrapper<>(condition)));
    }

    /**
     * 根据身份证号查询条数
     * @param idNumber 身份证号
     * @return
     */
    @GetMapping("/count/{idNumber}")
    public R getIdNumberCount(@PathVariable("idNumber") String idNumber) {
        SysUserinfo condition = new SysUserinfo();
        condition.setIdNumber(idNumber);
        return R.ok(sysUserinfoService.count(new QueryWrapper<>(condition)));
    }

    /**
     * 根据身份证号查询用户详细信息
     * @param idNumber 身份证号
     * @return
     */
    @GetMapping("/details/idNumber/{idNumber}")
    public R detailsIdNumber(@PathVariable("idNumber") String idNumber) {
        SysUserinfo condition = new SysUserinfo();
        condition.setIdNumber(idNumber);
        return R.ok(sysUserinfoService.getOne(new QueryWrapper<>(condition)));
    }

    /**
     * 根据当前用户信息获取id
     * @return
     */
    @GetMapping("/getId")
    public R getUserInfoId() {
        CloudUser user = SecurityUtils.getUser();
        SysUserinfo condition = new SysUserinfo();
        condition.setUserId(user.getId());
        condition = sysUserinfoService.getOne(new QueryWrapper<>(condition));
        if (condition == null){
            return R.ok(0);
        }
        return R.ok(condition.getId());
    }

    /**
     * 根据id获取用户
     */
    @GetMapping("/info/{id}")
    public R getUserInfoById(@PathVariable("id") Long id) {
        return R.ok(sysUserinfoService.getById(id));
    }

    /**
     * 获取电话号码
     * @return
     */
    @PostMapping("/getMobiles")
    public R<Map<String,String>> getMobiles(@RequestBody List<String> userNumbers) {
        return sysUserinfoService.getMobiles(userNumbers);
    }

    @GetMapping("/tree")
    public R getTree() {
        return R.ok(sysUserinfoService.selectTree());
    }

    /**
     * 同步数据
     * @return
     */
    @Inner
    @PostMapping("/syncData")
    public R syncData(){
        return this.sysUserinfoService.updateRemoteDatabase();
    }

    /**
     * 同步OA数据
     * @return
     */
    @Inner
    @PostMapping("/syncOaData")
    public R syncOaData() throws InterruptedException {
        return this.sysUserinfoService.syncOaData();
    }

    @PostMapping("/testSyncOaData")
    public R testSyncOaData() throws InterruptedException {
        return this.sysUserinfoService.syncOaData();
    }

    @GetMapping("/getUserinfoId/{personNum}")
    public R getUserinfoId(@PathVariable("personNum") String personNum){
        SysUserinfo condition = new SysUserinfo();
        condition.setPersonNumber(personNum);
        return R.ok(sysUserinfoService.getOne(new QueryWrapper<>(condition)).getId());
    }


    /**
     * 获取userId
     * @return
     */
    @Inner
    @PostMapping("/getUserIds")
    public R<List<Long>> getUserIds(@RequestBody List<Long> userInfoIds) {
        if (userInfoIds !=null && userInfoIds.size()>0){
           List<Long> userIds =  this.sysUserinfoService.list(Wrappers.<SysUserinfo>lambdaQuery().select(SysUserinfo::getUserId).in(SysUserinfo::getId,userInfoIds))
                    .stream().map(SysUserinfo::getUserId).collect(Collectors.toList());
           return R.ok(userIds);
        }
        return R.ok(new ArrayList<>());
    }

    @Inner
    @PostMapping("/getUserDetailInfoList")
    public R<List<UserInfoDeptVO>> getUserDetailInfoList(@RequestBody UserInfoParamsDTO userInfoParamsDTO){
        return R.ok(sysUserinfoService.getUserDetailInfoList(userInfoParamsDTO));
    }

}
